package top.hzy520.common;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: HouZeYu
 * @Description:  获取需要切换的库的名字
 * @Date: Created in 14:21 2018/8/15
 */
public class DynamicDataSourceHolder {

    private static  final  String SLAVE_1="slave_1";
    private static  final  String SLAVE_2="slave_2";
    private static final  String MASTER="master";
     /**并发integer**/
    private static AtomicInteger counter=new AtomicInteger(-1);

    private static  final  ThreadLocal<String> holder=new ThreadLocal<String>();

           public static  void setDataSource(DataSourceType dataSourceType){
            if (dataSourceType==DataSourceType.MASTER){
                System.out.println("-----------MASTER--------------");
                holder.set(MASTER);
            }else if (dataSourceType==DataSourceType.SLAVE){
                holder.set(RoundRobinSlaveKey());
            }

        }
        public static String getDataSource(){
            return holder.get();
        }
        /**--轮询选择slave1和slave2-**/
        private static String RoundRobinSlaveKey() {
            Integer index=counter.incrementAndGet()%2;
            if (counter.get()>999){
                counter.set(-1);
            }
            if (index==0){
                System.out.println("-----------SLAVE1--------------");
                return SLAVE_1;
            }else {
                System.out.println("-----------SLAVE2--------------");
                return SLAVE_2;
            }
    }
}
